package org.rslai.autotest.core.hook;

import java.net.MalformedURLException;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriverException;
import org.rslai.autotest.core.driver.IDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;

/**
 * 默认钩子程序
 * @author rslai
 */
@ContextConfiguration(locations = "classpath:cucumber.xml")
public class AutoTestHook {

	@Autowired
	IDriver iDriver;

	/**
	 * 在所有Scenario运行前执行
	 * @throws MalformedURLException
	 */
	@Before
	public void ScenarioBefore() throws MalformedURLException {
		this.iDriver.initDriver();
	}

	/**
	 * 在所有Scenario运行后执行
	 */
	@After
	public void ScenarioAfter(Scenario scenario) {

		// 出错时截屏（目前只支持输出到html报告）
		if (scenario.isFailed()) {
			try {
				byte[] screenshot = ((TakesScreenshot) this.iDriver.getDriver()).getScreenshotAs(OutputType.BYTES);
				scenario.embed(screenshot, "image/png");
			} catch (WebDriverException somePlatformsDontSupportScreenshots) {
				System.err.println(somePlatformsDontSupportScreenshots.getMessage());
			}
		}

		this.iDriver.quitDriver();
	}

}
